package com.example.demo.service;

import com.example.demo.util.MD5Util;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.sql.Timestamp;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class MailService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private JavaMailSender mailSender;
    @Resource
    private TemplateEngine templateEngine;

    @Value("${activeuser.url}")
    private String activeuserUrl;
    @Value("${spring.mail.username}")
    private String mailFrom;
    @Value("${mail.subject.active}")
    private String mailActiveSubject;

//    @Async   //这是一个异步方法
    public void sendActiveEmail(String email) {
        try {

            String secretKey = UUID.randomUUID().toString(); // 密钥
            String key = email + "$" + System.currentTimeMillis() + "$" + secretKey;
            String digitalSignature = MD5Util.encode(key);// 数字签名

            //保存到redis，30分钟过期
            //key是激活码,sid的值，value是邮箱地址
            stringRedisTemplate.opsForValue().set(digitalSignature,email,30, TimeUnit.MINUTES);
            //模板变量赋值
            Context context = new Context();
            context.setVariable("activeuserUrl",activeuserUrl+"?sid="
                    + digitalSignature);
            String emailContent = templateEngine.process("templates/mail_active.html",context);

            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(mailFrom);
            helper.setTo(email);

            helper.setSubject(mailActiveSubject);
            helper.setText(emailContent, true);

            mailSender.send(mimeMessage);
        } catch   (Exception e)  {
            e.printStackTrace();
        }
        System.out.println(email);

    }
}
